package com.hanko.web;

import com.hanko.repository.Person;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.data.elasticsearch.core.query.Query;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.List;

/**
 * @desc: RestHighLevelClient
 * @author: luodengxiong
 * @date: 2020-12-22 9:17:17
 **/
@Api(tags = "RestTemplate 操作方式")
@RestController
@RequestMapping("/RestTemplate")
public class RestTemplateController {

    @Autowired
    ElasticsearchRestTemplate elasticsearchRestTemplate;

    @Deprecated
    @ApiOperation(value = "通过ElasticsearchRestTemplate实现词频统计")
    @GetMapping("aggregations")
    public String aggregations() throws IOException {
        TermsAggregationBuilder aggregation = AggregationBuilders.terms("person-aggregate")
                .field("firstname");
        Query query = new NativeSearchQueryBuilder()
                .addAggregation(aggregation)
                .build();

        SearchHits<Person> searchHits = elasticsearchRestTemplate.search(query, Person.class);
        Aggregations aggregations = searchHits.getAggregations();
        Terms byCompanyAggregation = aggregations.get("person-aggregate");
        List<? extends Terms.Bucket> elasticBucket = byCompanyAggregation.getBuckets();
        StringBuilder sv = new StringBuilder();
        elasticBucket.forEach(el -> {
            sv.append("key:" + el.getKeyAsString());
            sv.append("doc_count:" + el.getDocCount());
        });
        return sv.toString();
    }

}
